<template>
  <div class="tiny-list h-full">
    <n-card class="h-full shadow-sm rounded-16px">
      <template #header>
        <n-space :size="[0, 0]" justify="space-between" align="end">
          <n-space justify="end">
            <n-button size="small" type="primary" @click="openGetModal">
              <icon-fluent:save-copy-24-filled class="mr-5px" />
              获取对账单
            </n-button>
            <review-dropdown v-model:checkedData="checkedRowKeys" />
            <n-select
              v-model:value="settlementTypeValue"
              :disabled="rowData.length === 0"
              :options="settlementTypeOptions"
              size="small"
              class="ml-30px w-120px"
            />

            {{ counts === 0 ? counts : '' }}
          </n-space>
          <search-bar @click="getDataSource()" />
        </n-space>
      </template>
      <template #default>
        <loading-empty-wrapper class="h-full" :loading="loading" :empty="empty">
          <n-data-table
            :data="rowData"
            :row-key="rowKey"
            :columns="columns"
            :pagination="pagination"
            :bordered="false"
            :single-line="false"
            :row-props="rowProps"
            :scroll-x="1780"
            virtual-scroll
            flex-height
            size="small"
            class="h-full"
            striped
            @update:checked-row-keys="handleCheck"
          />
        </loading-empty-wrapper>
      </template>
    </n-card>
    <ul class="more-data">
      <li v-for="(item, index) in totalData" :key="index">
        <span>{{ item.name }}:</span>
        <span>{{ item.val }}</span>
      </li>
    </ul>
    <edit-modal v-model:visible="editVisible" :edit-data="editData" />
    <get-statement-modal v-model:visible="getVisible" />
  </div>
</template>

<script setup lang="tsx">
import { onMounted, ref, reactive, computed, watch, onUnmounted } from 'vue';
import { NText } from 'naive-ui';
import type { DataTableColumn, DataTableRowKey, PaginationProps } from 'naive-ui';
import { fetchPurchaseList } from '@/service';
import { useDemoContext } from '@/context';
import { useLoadingEmpty, useBoolean } from '@/hooks';
import ReviewDropdown from './components/edit-modal/components/SelectionDeleteBtn.vue';
import SearchBar from './components/SearchBar.vue';
import EditModal from './components/edit-modal/index.vue';
import GetStatementModal from './components/GetStatement.vue';

const { useProvide } = useDemoContext();
const { counts } = useProvide();

// 初始加载、模态窗口状态
const { loading, startLoading, endLoading, empty } = useLoadingEmpty();
const { bool: editVisible, setTrue: openEditModal } = useBoolean();
const { bool: getVisible, setTrue: openGetModal } = useBoolean();

// 获取接口数据并处理加载状态
async function getDataSource() {
  startLoading();
  const { data } = await fetchPurchaseList();
  if (data) {
    setDataSource(data);
    endLoading();
  }
}

// 处理获取的数据
const rowData = ref<any>([]);
const totalData = ref<any>([]);
const rowIds = ref<any>([]);
function setDataSource(data: any) {
  const { rows, total } = data;
  rowData.value = rows;
  totalData.value = total;
  rowIds.value = setRowIds(rows);
}

function setRowIds(data: any) {
  return data.map((d: any) => d.BILL_ID);
}

// 配置分页
const pagination: PaginationProps = reactive({
  page: 1,
  pageSize: 20,
  pageSlot: 7,
  showSizePicker: true,
  showQuickJumper: true,
  size: 'small',
  pageSizes: [10, 20, 50, 100, 200, 500],
  suffix({ itemCount }) {
    return `共${itemCount}条记录`;
  },
  onChange: (page: number) => {
    pagination.page = page;
  },
  onUpdatePageSize: (pageSize: number) => {
    pagination.pageSize = pageSize;
    pagination.page = 1;
  }
});

// 配置对账单类型选项
const settlementTypeValue = ref('1');
const settlementTypeOptions = ref([
  {
    label: '全部对账单',
    value: '1'
  },
  {
    label: '售前对账单',
    value: '2'
  },
  {
    label: '售后对账单',
    value: '3'
  }
]);

// 获取表格当前页总行数
const pager: any = pagination;
const pageItemTotal = computed(() => (pager.page - 1) * pager.pageSize);

// 配置表格列参数
const columns: DataTableColumn[] = [
  {
    title: '序号',
    key: 'serial',
    width: 50,
    align: 'center',
    fixed: 'left',
    render(_, index) {
      return `${index + 1 + pageItemTotal.value}`;
    }
  },
  {
    type: 'selection',
    width: 30,
    fixed: 'left'
  },
  {
    key: 'A.BILL_DATE',
    title: '单据日期',
    width: 100,
    sorter: 'default'
  },
  {
    key: 'A.BILL_NO',
    title: '单据编号',
    width: 180,
    sorter: 'default'
  },
  {
    key: 'A_DEPTID.DEPT_NAME',
    title: '部门名称',
    width: 160,
    sorter: 'default'
  },
  {
    key: 'A_OBJID.CUST_NAME',
    title: '供应商名称',
    minWidth: 220,
    sorter: 'default'
  },
  {
    key: 'A.JS_AMOUNT',
    title: '结算金额',
    width: 100,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT1',
    title: '损耗扣款金额',
    width: 120,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT2',
    title: '促销扣款金额',
    width: 120,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.JSKK_AMOUNT3',
    title: '调整金额',
    width: 100,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.KP_AMOUNT',
    title: '应开票金额',
    width: 120,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.KK_AMOUNT',
    title: '其他扣款金额',
    width: 120,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.AP_AMOUNT',
    title: '应付金额',
    width: 100,
    sorter: 'default',
    align: 'right'
  },
  {
    key: 'A.CONFIRM_PERSION_ID',
    title: '审核状态',
    width: 80,
    sorter: 'default',
    render: (row: any) => {
      if (row['A.CONFIRM_PERSION_ID'] !== null) {
        const textTypes: any = {
          '0': 'warning',
          '1': 'success',
          '2': 'primary'
        };
        const textNames: any = {
          '0': '未审核',
          '1': '已审核',
          '2': '待审核'
        };
        return <NText type={textTypes[row['A.CONFIRM_PERSION_ID']]}>{textNames[row['A.CONFIRM_PERSION_ID']]}</NText>;
      }
      return '';
    }
  },
  {
    key: 'A.TJ_STATUS',
    title: '处理状态',
    width: 80,
    sorter: 'default',
    render: (row: any) => {
      if (row['A.TJ_STATUS'] !== null) {
        const textTypes: any = {
          '0': 'warning',
          '1': 'primary',
          '2': 'error',
          '3': 'success'
        };
        const textNames: any = {
          '0': '未提交',
          '1': '已提交',
          '2': '已退回',
          '3': '受理通过'
        };
        return <NText type={textTypes[row['A.TJ_STATUS']]}>{textNames[row['A.TJ_STATUS']]}</NText>;
      }
      return '';
    }
  }
];

// 处理行选中数据
const rowKey = (row: any) => row.BILL_ID;
const checkedRowKeysRef = ref<DataTableRowKey[]>([]);
const checkedRowKeys = checkedRowKeysRef;
function handleCheck(rowKeys: DataTableRowKey[]) {
  checkedRowKeysRef.value = rowKeys;
}

// 双击表格行进入编辑弹窗
function rowProps(row: any) {
  return {
    style: '',
    ondblclick: () => {
      handleEdit(row);
    }
  };
}
const editData = ref<any>(null);
function handleEdit(row: any) {
  editData.value = row;
  openEditModal();
}

const setPage = watch(
  () => counts.value,
  newValue => {
    pagination.page = newValue;
  }
);

onUnmounted(() => {
  setPage();
});

onMounted(() => {
  getDataSource();
});
</script>

<style scoped>
.more-data {
  font-size: 12px;
  line-height: 100%;
  position: absolute;
  display: flex;
  align-items: center;
  width: calc(100% - 560px);
  height: 45px;
  left: 25px;
  bottom: 10px;
}
.more-data li {
  float: left;
  vertical-align: middle;
  margin-right: 15px;
}
.more-data li span {
  display: inline-block;
  white-space: nowrap;
}
.more-data li span:first-child {
  margin-right: 5px;
}
</style>
